require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const schedule = require('node-schedule');
const MedicineStatusService = require('./services/medicineStatus.service');

// 创建Express应用
const app = express();

// 配置中间件
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 连接MongoDB数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/medicine_db')
  .then(() => console.log('MongoDB连接成功'))
  .catch(err => console.error('MongoDB连接失败:', err));

// 导入路由
const authRoutes = require('./routes/auth.routes');
const medicineRoutes = require('./routes/medicine.routes');
const reminderRoutes = require('./routes/reminder.routes');

// 注册路由
app.use('/api/auth', authRoutes);
app.use('/api/medicines', medicineRoutes);
app.use('/api/reminders', reminderRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    success: false,
    message: err.message || '服务器内部错误'
  });
});

// 启动定时任务
const reminderJob = schedule.scheduleJob('*/1 * * * *', async () => {
  // TODO: 实现用药提醒检查逻辑
  console.log('检查用药提醒...');
});

// 启动药品状态更新定时任务
MedicineStatusService.startStatusUpdateJob();

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});